package org.sciom

object StringUtils {
  def newWithFormat(format: String, args: Array[Any]) : String = {
    val buffer = new StringBuilder

    var index = 0
    val length = format.length
    val argsLength = args.length
    var argsIndex = -1

    while(index < length) {
      if(format.charAt(index) == '%') {
        index += 1

        format.charAt(index) match {
          case 's' => {
            argsIndex += 1
            if(!(argsIndex < argsLength)) {
              println("StringUtils.newWithFormat missing param")
              return null
            }
            buffer.append(args(argsIndex).asInstanceOf[String])
          }
          case 'i' => {
            argsIndex += 1
            if(!(argsIndex < argsLength)) {
              println("StringUtils.newWithFormat missing param")
              return null
            }
            buffer.append(String.format("%i", List[Object](args(argsIndex).asInstanceOf[java.lang.Integer]).toArray))
          }
          case 'd' => {
            argsIndex += 1
            if(!(argsIndex < argsLength)) {
              println("StringUtils.newWithFormat missing param")
              return null
            }
            buffer.append(String.format("%i", List[Object](args(argsIndex).asInstanceOf[java.lang.Integer]).toArray))
          }
          case 'f' => {
            argsIndex += 1
            if(!(argsIndex < argsLength)) {
              println("StringUtils.newWithFormat missing param")
              return null
            }

            buffer.append(String.format("%f", List[Object](args(argsIndex).asInstanceOf[java.lang.Double]).toArray))
          }
          case 'p' => {
            println("StringUtils.newWithFormat can't support %p flag")
            return null
          }
          case '3' => {
            argsIndex += 1
            if(!(argsIndex < argsLength)) {
              println("StringUtils.newWithFormat missing param")
              return null
            }
            var amount = args(argsIndex).asInstanceOf[Int]
            while(amount > 0) {
              buffer.append(" ")
            }
          }
        }
      } else {
        buffer.append(format.charAt(index))
      }
      
      index += 1
    }

    buffer.toString
  }
}
